package com.aier.admin_new.service.impl;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Component;

import com.aier.admin_new.entity.Dynamic;
import com.aier.admin_new.entity.DynamicCR;
import com.aier.admin_new.entity.DynamicComment;
import com.aier.admin_new.entity.User;
import com.aier.admin_new.entity.mapper.DynamicCRRowMapper;
import com.aier.admin_new.entity.mapper.DynamicCommentRowMapper;
import com.aier.admin_new.entity.mapper.DynamicMessageRowMapper;
import com.aier.admin_new.entity.mapper.DynamicRowMapper;
import com.aier.admin_new.entity.mapper.UserRowMapper;
import com.aier.admin_new.service.IDynamicService;
import com.aier.common.dao.ICommonDAO;

@Component("dynamicService_new")
public class DynamicServiceImpl implements IDynamicService {
	@Resource(name = "commonDao")
	private ICommonDAO commonDao;

	public void setCommonDao(ICommonDAO commonDao) {
		this.commonDao = commonDao;
	}

	@Override
	public int insertDynamic(Long uid, Integer sid, Long cid, String content,
			String img, Short type) {
		Dynamic d = new Dynamic();
		d.setUid(uid);
		d.setSid(sid);
		d.setCid(cid);
		d.setContent(content);
		d.setImg(img);
		d.setType(type);
		d.setOriginal((short) 0);
		d.setCdate(new Timestamp(new Date().getTime()));
		commonDao.insert(DynamicRowMapper.getPreparedStatementCreator(d),
				new GeneratedKeyHolder());
		return 1;
	}

	@Override
	public int insertOtherDynamic(Long uid, Integer sid, Long cid,
			String content, Long did, Short type) {
		Dynamic d = (Dynamic) commonDao.listByObject(
				"select * from dynamic where did = ?", new Object[] { did },
				new DynamicRowMapper());
		Long relativeid = did;
		// 将原创动态的转发次数+1
		commonDao
				.update("update dynamic set tcount = IFNULL(tcount,0)+1  where did = ?",
						new Object[] { relativeid });
		if (d.getOriginal() == 1) {
			relativeid = d.getRelativeid();
			commonDao
					.update("update dynamic set tcount = IFNULL(tcount,0)+1  where did = ?",
							new Object[] { relativeid });
		}
		Dynamic dy = new Dynamic();
		dy.setUid(uid);
		dy.setSid(sid);
		dy.setCid(cid);
		dy.setContent(content);
		dy.setType(type);
		dy.setOriginal((short) 1);
		dy.setCdate(new Timestamp(new Date().getTime()));
		dy.setRelativeid(relativeid);
		commonDao.insert(DynamicRowMapper.getPreparedStatementCreator(dy),
				new GeneratedKeyHolder());

		return 1;
	}

	@Override
	public Dynamic searchDynamic(Long did) {
		return (Dynamic) commonDao
				.listByObject(
						"select d.*,u.nickname,u.headimg  from dynamic d left join `user` u on d.uid = u.uid where d.did=?",
						new Object[] { did }, new DynamicRowMapper());
	}

	@Override
	public int insertDynamicComment(Long uid, Long did, String content,
			String picName) {
		commonDao
				.update("insert dynamic_comment(uid,did,content,cdate,picname) values(?,?,?,?,?)",
						new Object[] { uid, did, content,
								new Timestamp(new Date().getTime()), picName, });
		// 修改新鲜事的评论次数
		commonDao
				.update("update dynamic set ccount = IFNULL(ccount,0)+1  where did = ?",
						new Object[] { did });
		return 1;
	}

	@Override
	public int insertDCR(Long uid, Long dcid, String rname, String content) {
		commonDao
				.update("insert dynamic_comment_reply(uid,dcid,rname,content,cdate) values(?,?,?,?,?)",
						new Object[] { uid, dcid, rname, content,
								new Timestamp(new Date().getTime()) });

		DynamicComment dc = (DynamicComment) commonDao
				.listByObject(
						"select dc.did from dynamic_comment dc where dc.did = ? order by dc.cdate",
						new Object[] { dcid }, new DynamicCommentRowMapper());
		commonDao
				.update("update dynamic set ccount = IFNULL(ccount,0)+1  where did = ?",
						new Object[] { dc.getDid() });
		return 1;
	}

	@Override
	public int updateDynamicPraise(Long uid, Long did, int ptype) {
		List<?> obj = commonDao.list(
				"select * from dynamic_praise where uid =? and did=?",
				new Object[] { uid, did });
		if (ptype == 0) {
			// 新增赞的记录
			if (obj == null || obj.size() == 0) {
				commonDao
						.update("insert into dynamic_praise(uid,did,cdate) values (?,?,?)",
								new Object[] { uid, did,
										new Timestamp(new Date().getTime()) });
				// 修改动态的赞的次数
				commonDao
						.update("update dynamic set pcount = IFNULL(pcount,0)+1  where did = ?",
								new Object[] { did });
			}

		} else {
			// 删除赞的记录
			if (obj != null && obj.size() > 0) {
				commonDao.update(
						"delete from dynamic_praise where uid=? and did=?",
						new Object[] { uid, did });
				commonDao
						.update("update dynamic set pcount = IFNULL(pcount,0)-1  where did = ?",
								new Object[] { did });
			}
		}

		return 1;
	}

	@Override
	public Map<String, Object> searchAllDynamic(int page, int pagesize,
			Long uid, Long cid, Integer sid, Integer fuid) {
		// 学校动态
		if (sid != null) {
			String sql = " from dynamic d left join `user` u on d.uid = u.uid left join school_teacher st on u.uid=st.uid  where d.sid = ? and st.isadmin=1 and d.type=1 order by d.cdate desc";
			return commonDao.queryPage("select d.*,u.nickname,u.headimg" + sql,
					"select count(*)" + sql, page, pagesize,
					new Object[] { sid }, new Object[] { sid },
					new DynamicRowMapper());

		}
		// 班级动态
		if (cid != null) {
			String sql = " from dynamic d left join `user` u on d.uid = u.uid  left join school_teacher st on u.uid=st.uid  left join class_teacher ct on st.tid=ct.tid "
					+ "  where d.cid = ?  and ct.isadmin=1 and d.type=2 order by d.cdate desc";
			return commonDao.queryPage("select d.*,u.nickname,u.headimg" + sql,
					"select count(*)" + sql, page, pagesize,
					new Object[] { cid }, new Object[] { cid },
					new DynamicRowMapper());

		}
		// 个人动态
		if (uid != null) {
			String sql = "select d.*,u.nickname,u.headimg from dynamic d left join `user` u on d.uid = u.uid where d.uid = ? and d.type = 3  order by d.cdate desc";
			return commonDao.queryPage(sql, page, pagesize,
					new Object[] { uid }, new DynamicRowMapper());
		}
		// 好友动态
		String sql = "select d.*,u.nickname,u.headimg from dynamic d left join `user` u on d.uid = u.uid left join follow f on d.uid=f.fuid where (f.uid = ? and d.type = 3 and f.state=2) or d.uid = ?  order by d.cdate desc";
		return commonDao.queryPage(sql, page, pagesize, new Object[] { fuid,
				fuid }, new DynamicRowMapper());
	}

	@Override
	public int searchPraiseBySelf(Long uid, Long did) {
		List<?> obj = commonDao.list(
				"select * from dynamic_praise where uid =? and did=?",
				new Object[] { uid, did });
		if (obj == null || obj.size() == 0) {
			return 0;
		} else {
			return 1;
		}
	}

	@Override
	public Map<String, Object> searchCommentByDid(int page, int pagesize,
			Long did) {
		return commonDao
				.queryPage(
						"select dc.*, u.nickname, u.headimg from dynamic_comment dc left join `user` u "
								+ "on u.uid = dc.uid where dc.did = ? order by dc.cdate",
						page, pagesize, new Object[] { did },
						new DynamicCommentRowMapper());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DynamicCR> searchCRByDcid(Long dcid) {
		return (List<DynamicCR>) commonDao
				.list("select dcr.*,u.nickname,u.headimg from dynamic_comment_reply dcr left join `user` u "
						+ "on u.uid = dcr.uid where dcr.dcid = ? order by dcr.cdate",
						new Object[] { dcid }, new DynamicCRRowMapper());
	}

	@Override
	public int deleteDynamic(Long did) {
		return commonDao.update("delete from dynamic where did = ?",
				new Object[] { did });
	}

	@Override
	public int deleteComment(Long dcid) {
		// 删除评论
		return commonDao.update("delete from dynamic_comment where dcid = ?",
				new Object[] { dcid });
	}

	@Override
	public int deleteReply(Long dcrid) {
		// 删除回复
		return commonDao.update(
				"delete from dynamic_comment_reply where dcrid = ?",
				new Object[] { dcrid });
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> searchDynamicPraise(Long did) {
		return (List<User>) commonDao
				.list("select * from user u left join dynamic_praise dp on u.uid = dp.uid where dp.did = ?",
						new Object[] { did }, new UserRowMapper());
	}

	@SuppressWarnings("unchecked")
	@Override
	public Dynamic searchDynamicDetail(Long uid, Long did) {
		Dynamic d = (Dynamic) commonDao.listByObject(
				"select d.*,u.nickname,u.headimg from dynamic d left join `user` u "
						+ "on d.uid = u.uid where d.did = ?",
				new Object[] { did }, new DynamicRowMapper());
		// 转发
		if (d.getOriginal() == 1) {
			d.setDynamic(searchDynamic(d.getRelativeid()));
		}
		// 本人是否已赞过（1赞过0没赞）
		d.setPflag((short) searchPraiseBySelf(uid, did));

		List<DynamicComment> dcList = (List<DynamicComment>) commonDao
				.list("select dc.*, u.nickname, u.headimg from dynamic_comment dc "
						+ "left join `user` u on u.uid = dc.uid where dc.did = ? order by dc.cdate",
						new Object[] { did }, new DynamicCommentRowMapper());
		if (dcList != null && dcList.size() > 0) {
			for (DynamicComment dc : dcList) {
				dc.setDcrList(searchCRByDcid(dc.getDcid()));
			}
		}

		d.setDcList(dcList);
		return d;
	}

	@Override
	public Map<String, Object> searchDynamicMessage(int page, int pagesize,
			Long uid) {

		String sql = "select qqq.*,u.nickname,u.headimg from (select d.did,dc.uid,dc.content,dc.cdate,1 as type from dynamic_comment dc "
				+ "left join dynamic d on dc.did = d.did where d.uid = ? and d.type = 3 union select d.did,dcr.uid,dcr.content,dcr.cdate,"
				+ "2 as type from dynamic_comment_reply dcr left join dynamic_comment dc on dcr.dcid = dc.dcid left join dynamic d "
				+ "on dc.did = d.did where dc.uid = ? union select d.did,dp.uid,null as content,dp.cdate,3 as type from dynamic_praise dp "
				+ "left join dynamic d on dp.did = d.did where d.uid = ? and d.type = 3 ) as qqq left join `user` u on u.uid = qqq.uid "
				+ "order by qqq.cdate desc";

		String sql_count = "select count(*) from (select d.did,dc.uid,dc.content,dc.cdate,1 as type from dynamic_comment dc "
				+ "left join dynamic d on dc.did = d.did where d.uid = ? and d.type = 3 union select d.did,dcr.uid,dcr.content,dcr.cdate,"
				+ "2 as type from dynamic_comment_reply dcr left join dynamic_comment dc on dcr.dcid = dc.dcid left join dynamic d "
				+ "on dc.did = d.did where dc.uid = ? union select d.did,dp.uid,null as content,dp.cdate,3 as type from dynamic_praise dp "
				+ "left join dynamic d on dp.did = d.did where d.uid = ? and d.type = 3 ) as qqq ";
		return commonDao.queryPage(sql, sql_count, page, pagesize,
				new Object[] { uid, uid, uid }, new Object[] { uid, uid, uid },
				new DynamicMessageRowMapper());
	}

	@Override
	public Dynamic searchDynamic(Integer sid) {
		return (Dynamic) commonDao
				.listByObject(
						"select * from dynamic where sid = ? order by cdate desc limit 1",
						new Object[] { sid }, new DynamicRowMapper());
	}

}
